/*
 *    This file is part of CeluMap.
 *
 *    CeluMap is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU Lesser General Public License as published by
 *    the Free Software Foundation; either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    CeluMap is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    Copyright 2006, 2007, 2008 Gonzalo Merayo
 *    gonzalo (at) celumap.com.ar
 *    www.celumap.com.ar
 *
 */

package mapWriters;

import figures.Figure;
import figures.basic.NameManager;
import figures.basic.PoliLine;

import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;


public class BaseMapWriter implements MapWriter {

	List<Figure> lfigs = new LinkedList<Figure>();
	NameManager nm = new NameManager();
	
	public void addFigure(Figure f) {
		//lfigs.add(f);
		if(f instanceof PoliLine){
			((PoliLine)f).changeOffsetManager(nm);
		}
		
		List<Figure> tmp= new LinkedList<Figure>();
		boolean menor= false;
		int x=-1;
		for(Figure i:lfigs){
			x = i.getBoundingBox().bbxi;
			if(menor || x<f.getBoundingBox().bbxi){
				tmp.add(i);
			}else{
				menor = true;
				tmp.add(f);
				tmp.add(i);
			}
		}
		if(x<f.getBoundingBox().bbxi){
			tmp.add(f);
		}
		lfigs = tmp;
		
	}
	

	public void write(DataOutputStream os) throws IOException {
		os.writeInt(lfigs.size());
		nm.unload(os);
		for(Figure f:lfigs){
			Unloader.unload(os,f);
		}
	}

	
	public static void main(String[] args){
		BaseMapWriter b = new BaseMapWriter();
		try {
			b.write(new DataOutputStream(new FileOutputStream("empty.map")));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
